﻿using LayuiMvc.DataEntity.IdentityEntity;
using LayuiMvc.DataModel.Identity;
using LayuiMvcUtil.Exception;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LayuiMvc.Logic.Identity
{
    /// <summary>
    /// 登录管理器
    /// </summary>
    public class IdentitySignInManager:SignInManager<IdentityUserEntity,int>
    {
        public IdentitySignInManager(IdentityUserManager userManager,IAuthenticationManager authenticationManager) : base(userManager, authenticationManager)
        {

        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="loginModel">用户登录业务模型类</param>
        /// <returns></returns>
        public async Task UserLoginAsync(UserLoginModel loginModel)
        {
            //根据手机号码、邮箱查找用户
            IdentityUserEntity userEntity = await base.UserManager.Users.FirstOrDefaultAsync(m => m.PhoneNumber == loginModel.LoginName || m.Email == loginModel.LoginName);

            if (userEntity==null)
            {
                throw new CustomException("用户不存在");
            }
            if (userEntity.IsBanned)
            {
                throw new CustomException("用户已经被禁用了，请联系管理员");
            }


            /*
             * userName:登录用户名
             * password:密码
             * isPersistent:是否记住登录
             * shouldLockout:当登录失败超过一定次数的时候，锁定账户
             */

            SignInStatus status = await base.PasswordSignInAsync(userEntity.UserName, loginModel.Password, loginModel.IsRember, false);

            if (status==SignInStatus.Failure)
            {
                throw new CustomException("登录密码错误");
            }
        }


        /// <summary>
        /// 登录管理器创建方法
        /// </summary>
        /// <param name="options"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static IdentitySignInManager Create(IdentityFactoryOptions<IdentitySignInManager> options, IOwinContext context)
        {
            IdentityUserManager userManager = context.GetUserManager<IdentityUserManager>();

            IdentitySignInManager signInManager = new IdentitySignInManager(userManager, context.Authentication);

            return signInManager;
        }
    }
}
